package com.weimob.mcloud.wechatwork.customer.mq.userPermission.handler.logicHandler;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.CustomerEmployeeRelation;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.customer.ExternalUserTypeEnum;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerService;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.mq.handler.externaluser.AddCorpExternaluserSecondHandler;
import com.weimob.mcloud.wechatwork.customer.mq.userPermission.dto.EmployeeVidsDTO;
import com.weimob.mcloud.wechatwork.customer.service.user.service.CustomerExport;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.mcloud.wechatwork.customer.third.customer.CustomerThird;
import com.weimob.soa.common.response.SoaResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 员工权限变更-更新客户的vid权限
 *
 * @author yuanhao
 */
@Slf4j
@Component
public class CustomerPermissionHandler implements PermisssionChangeHandler {

    @Autowired
    private CustomerExport customerExport;

    @Value("${customer.ids.handler.partitioncount:100}")
    private Integer partitionCount;

    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Reference
    private PrivateSphereService privateSphereService;

    @Autowired
    private CustomerThird customerThird;

    @Autowired
    private AddCorpExternaluserSecondHandler addCorpExternaluserSecondHandler;

    @Reference
    CustomerService customerService;

    @Override
    public void updatePermission(List<? extends EmployeeVidsDTO> list, Integer msgType) {
        log.info("客户模块处理员工数据隔离变化:{}", JSON.toJSONString(list));

        // 1、获取所有corpid和员工
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        Map<String, Set<String>> corpIdMap = new HashMap<>();
        for (EmployeeVidsDTO employeeVidsDTO : list) {
            Set<String> employeeIdSet;
            if (corpIdMap.containsKey(employeeVidsDTO.getCorpId())) {
                employeeIdSet = corpIdMap.get(employeeVidsDTO.getCorpId());
            } else {
                employeeIdSet = new HashSet<>();
                corpIdMap.put(employeeVidsDTO.getCorpId(), employeeIdSet);
            }
            if (employeeVidsDTO.getEmployeeId() != null) {
                employeeIdSet.add(employeeVidsDTO.getEmployeeId());
            }
        }

        Set<String> corpIdSet = corpIdMap.keySet();
        if (CollectionUtils.isEmpty(corpIdSet)) {
            return;
        }

        // 2、corpid维度循环处理
        for (String corpId : corpIdSet) {
            Set<String> employeeIdSet = corpIdMap.get(corpId);

            if (CollectionUtils.isEmpty(employeeIdSet)) {
                continue;
            }

            // 2.1、查出员工的客户
            //滚动查询，获取所有的当前员工ids对应的客户员工关系数据
            List<CustomerEmployeeRelation> relationList = customerServiceProxy.scrollRelationByEmpIds(Lists.newArrayList(employeeIdSet), corpId, null);
            if (CollectionUtils.isEmpty(relationList)) {
                continue;
            }
            // 2.2、获取客户信息
            List<String> customerIdList = relationList.stream().map(CustomerEmployeeRelation::getCustomerId).distinct().collect(Collectors.toList());
            List<List<String>> customerIdPartition = Lists.partition(customerIdList, partitionCount);
            List<Customer> customerList = new ArrayList<>();
            for (List<String> customerIdListItem: customerIdPartition) {
                try {
                    List<Customer> customerList1 = customerServiceProxy.fetchCustomerByIds(customerIdListItem, null, null, CustomerStatusEnum.DEFAULT);
                    customerList.addAll(customerList1);
                } catch (Exception e) {
                    log.error("查询客户数据失败,error", e);
                }
            }

            // 2.3、客户同步ES隔离信息
            for (Customer customer : customerList) {
                PrivateSphere privateSphere = new PrivateSphere();
                privateSphere.setCorpId(customer.getCorpId());
                SoaResponse<PrivateSphere, Void> privateSphereResponse = privateSphereService.fetch(privateSphere);
                if (0L != Long.parseLong(privateSphereResponse.getReturnCode()) || Objects.isNull(privateSphereResponse.getResponseVo())) {
                    log.info("处理授权员工变更查询私域信息失败:{}", JSON.toJSONString(privateSphere));
                    return;
                }
                privateSphere = privateSphereResponse.getResponseVo();

                // 获取wid
                Long superWid = customerThird.getSuperWid(privateSphere.getBosId(), customer.getExternalUserid(), privateSphere.getCorpId());

                // 触发客户变更ES同步
                if(ExternalUserTypeEnum.WECHAT_CUSTOMER.getCode().equals(customer.getExternalUserType().getCode())
                    && superWid != null) {
                    addCorpExternaluserSecondHandler.updateCustomerSearchHisMsg(superWid, privateSphere.getBosId(),
                            privateSphere.getProductInstanceId(), privateSphere.getProductId());
                }

            }


        }

    }


}
